package main

import (
	"crypto/md5"
	"fmt"
	"gitee.com/c_z/finsur_spider/utils"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type Spider struct {
	cntxt   string
	URI     string
	Proxy   *http.Client
	GetReq  *http.Request
	PostReq *http.Request
}

func (s *Spider) Init() {
	s.Proxy = &http.Client{}
	s.GetReq, _ = http.NewRequest("GET", s.URI, nil)
	s.GetReq.Header.Add("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Mobile Safari/537.36")
	s.GetReq.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
	s.GetReq.Header.Add("Accept-Encoding", "gzip, deflate")
	s.GetReq.Header.Add("Connection", "keep-alive")
	/*
		postBuf := ""
		s.PostReq, _ = http.NewRequest("POST", s.URI, nil)
		s.PostReq.Header.Add("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Mobile Safari/537.36")
		s.GetReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	*/
}

func (s *Spider) CheckMD5(rsp *http.Response) (bool, error) {
	defer rsp.Body.Close()
	body, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return true, err
	}
	h := md5.New()
	h.Write(body)

	cntxt := fmt.Sprintf("%x", h.Sum(nil))
	if s.cntxt != cntxt {
		s.cntxt = cntxt
		return false, nil
	} else {
		return true, nil
	}
}

func (s *Spider) Capture() (resp *http.Response, err error) {
	resp, err = s.Proxy.Do(s.GetReq)
	if err != nil {
		utils.Logger.Error("Get Error:%s", err.Error())
		// continue
		return nil, err
	}
	return
}

func Start() {
	utils.Logger.Info("Start...")
	spider := &Spider{
		cntxt: "",
		URI:   Config.WatchURI,
	}
	spider.Init()
	for {
		time.Sleep(1 * time.Second)

		rsp, err := spider.Capture()
		if err != nil {
			utils.Logger.Error("Capture error:%s", err.Error())
			continue
		}
		fmt.Printf("Old MD5:%s \n", spider.cntxt)
		same, err := spider.CheckMD5(rsp)
		if err != nil {
			utils.Logger.Error("CheckMD5 error:%s", err.Error())
			continue
		}
		if !same {
			fmt.Printf("New MD5 is %s \n", spider.cntxt)
			sendMail()
			doRegist()
		}
	}
}

func sendMail() {
	utils.Mail("The Finsur Updated")
}

func doRegist() {
	http.PostForm(Config.WatchURI,
		url.Values{
			"amunt":   {"49"},
			"email":   {"278608029@qq.com"},
			"address": {"0xfa9d90c7092bE5aeaE1b4Ac3015011C30C1190a3"},
			"agree":   {"on"},
		})
	utils.Mail("Regist for cz.theng.rich@gmail.com ")
}
